package com.tupi.project.base;


import com.tupi.project.component.RxBus;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 基于Rx的Presenter封装,控制订阅的生命周期
 */
public abstract class RxPresenter<T extends BaseView> implements BasePresenter<T>
{
    protected T mView;
    protected CompositeDisposable mCompositeDisposable;
    
    public RxPresenter()
    {
        addEvent();
    }
    
    
    protected void unSubscribe()
    {
        if (mCompositeDisposable != null)
        {
            mCompositeDisposable.clear();
        }
    }
    
    protected void addSubscribe(Disposable subscription)
    {
        if (mCompositeDisposable == null)
        {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }
    
    protected <U> void addRxBusSubscribe(Class<U> eventType, Consumer<U> act)
    {
        if (mCompositeDisposable == null)
        {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(RxBus.getDefault().toDefaultFlowable(eventType, act));
    }
    
    @Override
    public void attachView(T view)
    {
        this.mView = view;
    }
    
    @Override
    public void detachView()
    {
        this.mView = null;
        unSubscribe();
    }
    
}
